from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer

class ApiResponse(Response):
    """
    统一API响应格式
    """
    def __init__(self, code=200, message='success', data=None,
                 status=None, headers=None, **kwargs):
        """
        初始化API响应
        
        :param code: 业务状态码
        :param message: 提示消息
        :param data: 返回数据
        :param status: HTTP状态码
        :param headers: 响应头
        :param kwargs: 额外参数
        """
        response_data = {
            'code': code,
            'message': message,
            'data': data or None
        }
        # 合并额外参数
        response_data.update(kwargs)
        
        super().__init__(
            data=response_data, 
            status=status, 
            headers=headers,
            content_type='application/json'
        )
         # 强制设置JSON渲染器并立即渲染
        self.accepted_renderer = JSONRenderer()
        self.accepted_media_type = 'application/json'
        self.renderer_context = {}
        self.render()

    @classmethod
    def success(cls, data=None, message='success', **kwargs):
        """
        快速创建成功响应
        """
        return cls(code=200, message=message, data=data, **kwargs)

    @classmethod
    def error(cls, code=400, message='error', data=None, **kwargs):
        """
        快速创建错误响应
        """
        return cls(code=code, message=message, data=data, **kwargs)

    @classmethod
    def server_error(cls, message='Internal Server Error', data=None, **kwargs):
        """
        服务器错误响应
        """
        return cls(code=500, message=message, data=data, status=500, **kwargs)

    @classmethod
    def not_found(cls, message='Not Found', data=None, **kwargs):
        """
        资源未找到响应
        """
        return cls(code=404, message=message, data=data, status=404, **kwargs)

    @classmethod
    def forbidden(cls, message='Forbidden', data=None, **kwargs):
        """
        禁止访问响应
        """
        return cls(code=403, message=message, data=data, status=403, **kwargs)

    @classmethod
    def unauthorized(cls, message='Unauthorized', data=None, **kwargs):
        """
        未授权响应
        """
        return cls(code=401, message=message, data=data, status=401, **kwargs)